package org.dg.iag.util;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

import org.restlet.Request;
import org.restlet.data.Form;
import org.restlet.resource.ServerResource;

import com.thoughtworks.xstream.io.copy.HierarchicalStreamCopier;
import com.thoughtworks.xstream.io.json.JsonWriter;
import com.thoughtworks.xstream.io.xml.XppReader;

public class RestletUtil {
	public static Map<String, String> getFiltersFromServerResource(ServerResource sr) {
		Form form					= sr.getQuery();
		HashMap<String, String> ret	= new HashMap<String, String>();
		String filterStr		= form.getFirstValue("filter");
		if ( filterStr != null ) {
			try {
				String [] filterPairList	= filterStr.split(",");
				for (int i=0; i<filterPairList.length ; i++) {
					String [] filterEl	= filterPairList[i].split("#");
					ret.put(filterEl[0], filterEl[1]);
				}
			}
			catch (NullPointerException e) {
				
			}
		
		}
		
		
		return ret;
	}
	
	public static String generateJsonFromXML( String xml ) {
		if (xml != null) {
			StringWriter sw					= new StringWriter(); 
			StringReader sr					= new StringReader(xml);
			HierarchicalStreamCopier hsc	= new HierarchicalStreamCopier();
			hsc.copy(new XppReader(sr), new JsonWriter(sw));
			String jsonRet					= sw.toString();
			String js2						= jsonRet.replaceAll("\"@", "\"");
			return js2;
		}
		return null;
	}
	
	public static String getPathFromRequest(Request request, String key) {
		String ret	= (String)request.getAttributes().get(key);
		if ( ret != null) {
			ret		= ret.replace(ApplicationConstants.XPATH_URL_SEPARATOR, "/");
		}
		return ret;
	}
	
	public static void populateParamsMap(Map<String,String> map, Request request) {
		for ( int i=1; i<=ApplicationConstants.MAX_PARAMS_IN_QUERY; i++ ) {
			String key						= RestletUtil.getPathFromRequest(request, "key"+i);
			if ( key != null) {
				String value				= (String)request.getAttributes().get("value"+i);
				value	= value.replace("%7C", "/");
				map.put(key, value);
			}
		}
	} 
	
	
}
